package com.google.code.jcooky.rpc.transport;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.commons.io.IOUtils;

import com.google.code.jcooky.rpc.connect.Connector;
import com.google.code.jcooky.rpc.connect.HttpConnector;

public class JSONTransport implements Transport {
	private Connector conn;
	
	public JSONTransport(Socket socket) {
		// standalone protocol
	}
	
	public JSONTransport(URL url) throws IOException {
		// http protocol
		conn = new HttpConnector(url);
	}

	public void send(String json) {
		OutputStream os = null;
		try {
			
			os = conn.getOutputStream();
			IOUtils.write(URLEncoder.encode(json, "UTF-8"), os);
			
		} catch(IOException e) {
			throw new RuntimeException(e);
		} finally {
			if(os != null) try { os.close(); } catch(IOException e) {}
		}
	}

	public String recv() {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			StringBuffer strBuf = new StringBuffer(1024);
			String line;
			while((line = reader.readLine()) != null) strBuf.append(line);
			return strBuf.toString();
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if(reader != null) try { reader.close(); } catch(IOException e) {}
		}
		
	}
}
